package com.peoit.honeycomb.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.peoit.honeycomb.application.ProjectApplication;
import com.peoit.honeycomb.domain.Accessory;
import com.peoit.honeycomb.domain.HoneycombProject;
import com.peoit.honeycomb.domain.Investment;
import com.peoit.honeycomb.domain.exception.UserNotExistException;
import com.peoit.honeycomb.dto.CommonResultJsonDto;
import com.peoit.honeycomb.dto.Config;
import com.peoit.honeycomb.dto.PageCommonResultDto;
import com.peoit.honeycomb.dto.ProjectDto;
import com.peoit.honeycomb.dto.ProjectQueryDto;

/**
 * Created by Bing.Zeng on 2015/9/24.
 */
@Controller
@RequestMapping("/admin/project")
public class ProjectController extends HoneycombBaseController {
	Logger logger = Logger.getLogger(ProjectController.class.getName());

	@Autowired
	ProjectApplication projectApplication;

	/**
	 * 分页列表
	 *
	 * @return
	 */
	@RequestMapping("/list/{offset}")
	public ModelAndView list(ProjectQueryDto dto, @PathVariable int offset) {
		dto.setOffset(offset);
		PageCommonResultDto pageCommonResultDto = new PageCommonResultDto();
		List<HoneycombProject> dtos = null;
		try {
			dtos = projectApplication.findByWherePage(dto);
		} catch (ParseException e) {
			pageCommonResultDto.setResult_code("500");
			pageCommonResultDto.setReason("Inter err" + e.getMessage());
		}

		long count = projectApplication.findByWhereCount(dto);
		pageCommonResultDto.setResult(dtos);
		pageCommonResultDto.setPageSize(dto.getPageSize());
		pageCommonResultDto.setCount(count);
		pageCommonResultDto.setOffset(offset);
		return view("/jsp/project/projectlist", pageCommonResultDto, dto);
	}

	/**
	 * 项目审核
	 *
	 * @param projectId
	 * @param passOrNot
	 *            是否审核通过
	 * @return
	 */
	@RequestMapping("/verify")
	public @ResponseBody CommonResultJsonDto verify(String projectId, boolean passOrNot) {
		CommonResultJsonDto result = CommonResultJsonDto.success("操作成功！！");
		boolean verify = projectApplication.verify(projectId, passOrNot);
		return result;
	}

	/**
	 * 项目延期
	 *
	 * @param projectId
	 * @param passOrNot
	 *            是否同意延期
	 * @return
	 */
	@RequestMapping("/postpone")
	public @ResponseBody CommonResultJsonDto postpone(String projectId, boolean passOrNot) {
		CommonResultJsonDto result = CommonResultJsonDto.success("操作成功！！");
		projectApplication.postpone(projectId, passOrNot);
		return result;
	}

	/**
	 * 设置保证金
	 * 
	 * @param projectId
	 * @return
	 */
	@RequestMapping("/toUpdateEarnestPercent")
	public ModelAndView updateEarnestPercent(String projectId) {
		ProjectDto dto = ProjectDto.toDto(projectApplication.find(HoneycombProject.class, projectId));
		return view("/jsp/project/setEarnest", dto);
	}

	/**
	 * 修改保证金百分比
	 * 
	 * @param projectId
	 * @param projectEarnestPercent
	 * @param investorEarnestPercent
	 * @return
	 */
	@RequestMapping("/updateEarnestPercent")
	public ModelAndView updateEarnestPercent(String projectId, double projectEarnestPercent,
			double investorEarnestPercent) {
		projectApplication.updateEarnestPercent(projectId, projectEarnestPercent, investorEarnestPercent);
		return view("redirect:/admin/project/list/0");
	}

	/**
	 * public @ResponseBody CommonResultJsonDto createProject(@RequestParam(
	 * required = false, value = "projectPictures" )MultipartFile[]
	 * projectPictures ,
	 *
	 * @RequestParam( required = false,value = "businessLicensePictures"
	 * )MultipartFile[] businessLicensePictures , @RequestParam( required =
	 * false , value = "creditReportPictures")MultipartFile[]
	 * creditReportPictures ,
	 * 
	 * @RequestParam(required = false ,value =
	 *                        "businessPermissionPictures")MultipartFile[]
	 *                        businessPermissionPictures , ProjectDto dto,
	 *                        HttpServletRequest request) { 发布项目
	 */
	@RequestMapping("/createProject")
	public @ResponseBody CommonResultJsonDto createProject(
			@RequestParam(required = false, value = "projectPictures") MultipartFile[] projectPictures,
			@RequestParam(required = false, value = "businessLicensePictures") MultipartFile[] businessLicensePictures,
			@RequestParam(required = false, value = "creditReportPictures") MultipartFile[] creditReportPictures,
			@RequestParam(required = false, value = "businessPermissionPictures") MultipartFile[] businessPermissionPictures,
			ProjectDto dto, HttpServletRequest request) {
		CommonResultJsonDto result = CommonResultJsonDto.success("成功！！");

		try {

			HoneycombProject project = ProjectDto.toProject(dto);
			project.setStatus(Config.waitingVerified);

			// 依次处理处理各个上传文件

			Set<Accessory> accesories = new HashSet<>();
			// 项目图片
			if (projectPictures != null && projectPictures.length > 0) {
				for (MultipartFile file : projectPictures) {
					String filePath = this.storeUploadFile(request, file);
					Accessory accessory = new Accessory();
					accessory.setFilePath(filePath);
					accessory.setProject(project);
					accessory.setType(Config.PROJECT_PICTURE);
					accessory.setCreateTime(new Date());
					accesories.add(accessory);
				}
			}

			// 营业执照图片
			if (businessLicensePictures != null && businessLicensePictures.length > 0) {
				for (MultipartFile file : businessLicensePictures) {
					String filePath = this.storeUploadFile(request, file);
					Accessory accessory = new Accessory();
					accessory.setFilePath(filePath);
					accessory.setProject(project);
					accessory.setType(Config.BUSINESS_LICENSE);
					accessory.setCreateTime(new Date());
					accesories.add(accessory);
				}
			}

			// 个人信用报告图片
			if (creditReportPictures != null && creditReportPictures.length > 0) {
				for (MultipartFile file : creditReportPictures) {
					String filePath = this.storeUploadFile(request, file);
					Accessory accessory = new Accessory();
					accessory.setFilePath(filePath);
					accessory.setProject(project);
					accessory.setType(Config.PERSONAL_CREDIT_REPORT);
					accessory.setCreateTime(new Date());
					accesories.add(accessory);
				}
			}

			// 行业许可证图片
			if (businessPermissionPictures != null && businessPermissionPictures.length > 0) {
				for (MultipartFile file : businessPermissionPictures) {
					String filePath = this.storeUploadFile(request, file);
					Accessory accessory = new Accessory();
					accessory.setFilePath(filePath);
					accessory.setProject(project);
					accessory.setType(Config.BUSINESS_PERMISSION);
					accessory.setCreateTime(new Date());
					accesories.add(accessory);
				}
			}
			project.setAccessories(accesories);

			projectApplication.create(dto.getUserId(), project);

		} catch (UserNotExistException ex) {
			ex.printStackTrace();
			result = CommonResultJsonDto.fail("用户不存在！！");
		} catch (Exception ex) {
			ex.printStackTrace();
			result = CommonResultJsonDto.fail(ex.getMessage());
		}
		return result;

	}

	/**
	 * 获取项目详情
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/projectDetail")
	public ModelAndView projectDetail(String id) {
		HoneycombProject project = projectApplication.find(HoneycombProject.class, id);
		return view("/jsp/project/projectDetail", ProjectDto.toDto(project));
	}

	/**
	 * 获取投资人
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/projectInvestor")
	public ModelAndView projectInvestor(String id) {
		HoneycombProject project = projectApplication.find(HoneycombProject.class, id);
		List<Investment> result = new ArrayList<Investment>();
		for (Investment investment : project.getInvestments()) {
			result.add(investment);
		}
		return view("/jsp/project/projectInvestor", result);
	}

	/**
	 * 启动项目
	 * 
	 * @param dto
	 * @return
	 */
	@RequestMapping("/startProject")
	public @ResponseBody CommonResultJsonDto startProject(ProjectQueryDto dto) {
		CommonResultJsonDto result = CommonResultJsonDto.success("操作成功！！");
		projectApplication.startProject(dto);
		return result;
	}

	/**
	 * 启动项目
	 * 
	 * @param dto
	 * @return
	 */
	@RequestMapping("/stopProject")
	public @ResponseBody CommonResultJsonDto stopProject(ProjectQueryDto dto) {
		CommonResultJsonDto result = CommonResultJsonDto.success("操作成功！！");
		projectApplication.stopProject(dto);
		return result;
	}

	/**
	 * 变更投资人状态
	 * 
	 * @param dto
	 * @return
	 */
	@RequestMapping("/changInvestStatus")
	public @ResponseBody CommonResultJsonDto changInvestStatus(String id, int status) {
		CommonResultJsonDto result = CommonResultJsonDto.success("操作成功！！");
		projectApplication.changeInvestStatus(id, status);
		return result;
	}
}
